using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Web.WebView2.Core;
using PaddleOCRSharp;
using Sunny.UI;
using OpenCvSharp;
using System.Drawing.Imaging;
using Serilog;

namespace WinApp.Services
{
    /// <summary>
    /// 辅助工具类
    /// </summary>
    internal class AuxHelper
    {
        /// <summary>
        /// 从WebView2中截取指定区域的图像
        /// </summary>
        /// <param name="webView2">WebView2控件实例</param>
        /// <param name="x">起始X坐标</param>
        /// <param name="y">起始Y坐标</param>
        /// <param name="width">截图宽度</param>
        /// <param name="height">截图高度</param>
        /// <returns>返回截取的图像</returns>
        public static async Task<Bitmap> CaptureWebViewAsync(Microsoft.Web.WebView2.WinForms.WebView2 webView2, int x, int y, int width, int height)
        {
            try
            {
                if (webView2 == null)
                {
                    throw new ArgumentNullException(nameof(webView2), "WebView2控件不能为空");
                }

                if (webView2.CoreWebView2 == null)
                {
                    throw new InvalidOperationException("WebView2尚未初始化完成，请等待CoreWebView2初始化");
                }

                // 确保坐标和尺寸有效
                if (width <= 0 || height <= 0)
                {
                    throw new ArgumentException($"无效的截图尺寸：宽度={width}, 高度={height}");
                }

                var screenshot = new Bitmap(width, height);
                using (var webViewMs = new MemoryStream())
                {
                    // 捕获整个WebView2的截图
                    await webView2.CoreWebView2.CapturePreviewAsync(CoreWebView2CapturePreviewImageFormat.Png, webViewMs);
                    webViewMs.Position = 0;

                    using (var fullImage = Image.FromStream(webViewMs))
                    {
                        // 检查截图区域是否超出范围
                        if (x + width > fullImage.Width || y + height > fullImage.Height)
                        {
                            throw new ArgumentException($"截图区域超出范围：x={x}, y={y}, width={width}, height={height}, 图像大小：{fullImage.Width}x{fullImage.Height}");
                        }

                        using (var graphics = Graphics.FromImage(screenshot))
                        {
                            graphics.DrawImage(fullImage,
                                new Rectangle(0, 0, width, height),
                                new Rectangle(x, y, width, height),
                                GraphicsUnit.Pixel);
                        }
                    }
                }
                return screenshot;
            }
            catch (Exception ex)
            {
                Log.Error(ex, $"WebView2截图失败：x={x}, y={y}, width={width}, height={height}");
                throw;
            }
        }

        /// <summary>
        /// 将Bitmap转换为OpenCV的Mat对象
        /// </summary>
        private static Mat BitmapToMat(Bitmap bitmap)
        {
            try
            {
                using (var ms = new MemoryStream())
                {
                    // 将Bitmap保存为PNG格式到内存流
                    bitmap.Save(ms, ImageFormat.Png);
                    
                    // 从内存流创建Mat对象
                    var imageBytes = ms.ToArray();
                    var mat = Cv2.ImDecode(imageBytes, ImreadModes.Color);
                    
                    return mat;
                }
            }
            catch (Exception ex)
            {
                Log.Error($"Bitmap转Mat失败：{ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 使用OpenCV进行图像匹配
        /// </summary>
        /// <param name="avatar">需要匹配的图像</param>
        /// <param name="region">模板图像</param>
        /// <param name="threshold">匹配阈值(0~1)</param>
        /// <returns>返回(是否匹配, 匹配度, 匹配矩形)</returns>
        public static (bool IsMatch, double Similarity, Rectangle MatchRect) MatchAvatar(Image avatar, Image region, double threshold)
        {
            try
            {
                using (var avatarMat = BitmapToMat(new Bitmap(avatar)))
                using (var regionMat = BitmapToMat(new Bitmap(region)))
                {
                    // 创建结果矩阵
                    using (var result = new Mat())
                    {
                        // 进行模板匹配
                        Cv2.MatchTemplate(avatarMat, regionMat, result, TemplateMatchModes.CCoeffNormed);

                        // 获取最大匹配值和位置
                        Cv2.MinMaxLoc(result, out _, out double maxVal, out _, out OpenCvSharp.Point maxLoc);

                        // 计算匹配矩形
                        var matchRect = new Rectangle(
                            maxLoc.X,
                            maxLoc.Y,
                            regionMat.Width,
                            regionMat.Height
                        );

                        // 判断是否匹配（匹配度大于阈值）
                        bool isMatch = maxVal >= threshold;

                        return (isMatch, maxVal, matchRect);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error($"图像匹配失败：{ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 对图像进行OCR文字识别
        /// </summary>
        /// <param name="image">要识别的图像</param>
        /// <returns>返回识别到的文本，如果未识别到则返回空字符串</returns>
        public static string RecognizeText(Bitmap image)
        {
            try
            {
                // 初始化OCR引擎
                OCRModelConfig config = null; // 使用默认配置
                OCRParameter oCRParameter = new OCRParameter();

                PaddleOCREngine engine = new PaddleOCREngine(config, oCRParameter);
                // 执行文字识别
                OCRResult ocrResult = engine.DetectText(image);

                string recognizedText = string.Empty;
                if (ocrResult != null && ocrResult.Text != null)
                {
                    recognizedText = ocrResult.Text;                    
                }
                engine.Dispose();
                return recognizedText;
            }
            catch (Exception ex)
            {
                Log.Error($"OCR识别失败：{ex.Message}");                
                
                throw ex;
            }
        }
    }
}
